import React, { useRef, useState } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { EnvironmentalSensor } from '../../../types';

interface EnvironmentalSensorProps {
  sensor: EnvironmentalSensor;
  isSelected?: boolean;
  onClick?: () => void;
}

const EnvironmentalSensorComponent: React.FC<EnvironmentalSensorProps> = ({
  sensor,
  isSelected = false,
  onClick
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const [isHovered, setIsHovered] = useState(false);
  const pulseRef = useRef<THREE.Mesh>(null);
  
  // 动画参数
  const [pulseScale, setPulseScale] = useState(1);
  const pulseDirection = useRef(1);

  // 根据传感器类型获取图标颜色
  const getIconColor = (): string => {
    switch (sensor.type) {
      case 'temperature':
        return '#FF5722'; // 橙色
      case 'humidity':
        return '#2196F3'; // 蓝色
      case 'smoke':
        return '#9E9E9E'; // 灰色
      case 'waterLeak':
        return '#03A9F4'; // 亮蓝色
      case 'airFlow':
        return '#4CAF50'; // 绿色
      default:
        return '#673AB7'; // 紫色
    }
  };

  // 根据传感器状态获取颜色
  const getStatusColor = (): string => {
    switch (sensor.status) {
      case 'normal':
        return '#4CAF50';
      case 'warning':
        return '#FFC107';
      case 'critical':
        return '#F44336';
      default:
        return '#2196F3';
    }
  };

  // 处理点击事件
  const handleClick = (event: React.MouseEvent) => {
    event.stopPropagation();
    if (onClick) {
      onClick();
    }
  };

  // 处理鼠标悬停事件
  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
  };

  // 脉冲动画效果
  useFrame((state) => {
    // 更新脉冲大小
    setPulseScale(prevScale => {
      const newScale = prevScale + (pulseDirection.current * 0.02);
      
      if (newScale > 1.5) {
        pulseDirection.current = -1;
        return 1.5;
      }
      if (newScale < 1) {
        pulseDirection.current = 1;
        return 1;
      }
      
      return newScale;
    });

    // 为警告和严重状态添加呼吸动画效果
    if (pulseRef.current && (sensor.status === 'warning' || sensor.status === 'critical')) {
      const material = pulseRef.current.material as THREE.MeshStandardMaterial;
      const pulse = Math.sin(state.clock.getElapsedTime() * 2) * 0.5 + 0.5;
      const baseIntensity = sensor.status === 'warning' ? 0.5 : 0.8;
      material.emissiveIntensity = baseIntensity + pulse * (sensor.status === 'warning' ? 0.3 : 0.4);
    }
  });

  // 根据传感器类型创建不同的图标
  const renderSensorIcon = () => {
    const color = getIconColor();
    
    switch (sensor.type) {
      case 'temperature':
        // 温度传感器图标 - 温度计形状
        return (
          <mesh position={[0, 0, 0]}>
            <cylinderGeometry args={[0.05, 0.05, 0.2, 8]} />
            <meshStandardMaterial color={color} roughness={0.3} metalness={0.2} />
          </mesh>
        );
        
      case 'humidity':
        // 湿度传感器图标 - 水滴形状
        return (
          <mesh position={[0, 0, 0]} rotation={[Math.PI / 2, 0, 0]}>
            <cylinderGeometry args={[0.07, 0.05, 0.15, 8]} />
            <meshStandardMaterial color={color} roughness={0.3} metalness={0.2} />
          </mesh>
        );
        
      case 'smoke':
        // 烟雾传感器图标 - 三角形
        return (
          <mesh position={[0, 0, 0]} rotation={[-Math.PI / 2, 0, 0]}>
            <coneGeometry args={[0.08, 0.2, 3]} />
            <meshStandardMaterial color={color} roughness={0.3} metalness={0.2} />
          </mesh>
        );
        
      case 'waterLeak':
        // 水浸传感器图标 - 方形
        return (
          <mesh position={[0, 0, 0]}>
            <boxGeometry args={[0.12, 0.12, 0.05]} />
            <meshStandardMaterial color={color} roughness={0.3} metalness={0.2} />
          </mesh>
        );
        
      case 'airFlow':
        // 气流传感器图标 - 圆形
        return (
          <mesh position={[0, 0, 0]}>
            <circleGeometry args={[0.08, 8]} />
            <meshStandardMaterial color={color} roughness={0.3} metalness={0.2} />
          </mesh>
        );
        
      default:
        // 默认图标 - 球体
        return (
          <mesh position={[0, 0, 0]}>
            <sphereGeometry args={[0.08]} />
            <meshStandardMaterial color={color} roughness={0.3} metalness={0.2} />
          </mesh>
        );
    }
  };

  return (
    <group
      ref={groupRef}
      position={[sensor.position.x, sensor.position.y, sensor.position.z]}
      onClick={handleClick}
      onPointerEnter={handleMouseEnter}
      onPointerLeave={handleMouseLeave}
    >
      {/* 安装底座 */}
      <mesh position={[0, -0.15, 0]}>
        <cylinderGeometry args={[0.15, 0.15, 0.05, 8]} />
        <meshStandardMaterial color="#666666" roughness={0.8} metalness={0.4} />
      </mesh>
      
      {/* 传感器支柱 */}
      <mesh position={[0, -0.05, 0]}>
        <cylinderGeometry args={[0.05, 0.05, 0.1, 8]} />
        <meshStandardMaterial color="#999999" roughness={0.6} metalness={0.5} />
      </mesh>
      
      {/* 传感器主体 */}
      <mesh position={[0, 0.05, 0]}>
        <sphereGeometry args={[0.1]} />
        <meshStandardMaterial
          color={isSelected ? '#00f0ff' : '#1e293b'}
          roughness={0.2}
          metalness={0.8}
          transparent
          opacity={isSelected ? 0.9 : 0.7}
        />
      </mesh>
      
      {/* 传感器图标 */}
      <group position={[0, 0.05, 0]}>
        {renderSensorIcon()}
      </group>
      
      {/* 状态指示器 */}
      <mesh
        position={[0, 0.2, 0]}
        ref={pulseRef}
        scale={[pulseScale, pulseScale, pulseScale]}
      >
        <sphereGeometry args={[0.06]} />
        <meshStandardMaterial
          color={getStatusColor()}
          emissive={getStatusColor()}
          emissiveIntensity={sensor.status === 'normal' ? 0.5 : sensor.status === 'warning' ? 0.8 : 1.2}
          transparent
          opacity={0.6}
          roughness={0.1}
          metalness={0.2}
        />
      </mesh>
      
      {/* 选中边框 */}
      {isSelected && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.SphereGeometry(0.15, 12, 12)
            ]}
          />
          <lineBasicMaterial
            color="#2196F3"
            linewidth={3}
          />
        </lineSegments>
      )}
      
      {/* 悬停效果 */}
      {isHovered && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.SphereGeometry(0.13, 12, 12)
            ]}
          />
          <lineBasicMaterial
            color="#64B5F6"
            linewidth={2}
          />
        </lineSegments>
      )}
    </group>
  );
};

export default React.memo(EnvironmentalSensorComponent);